package org.wangchaocheng.cloudgallery.handler;

import com.alibaba.cola.dto.Response;
import com.alibaba.cola.exception.BizException;

import cn.dev33.satoken.exception.NotLoginException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.wangchaocheng.cloudgallery.common.exception.ErrorEnum;
import org.wangchaocheng.cloudgallery.i18n.I18nFactory;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BizException.class)
    public Response businessExceptionHandler(BizException e) {
        log.error("BusinessException", e);
        return Response.buildFailure(e.getErrCode(), I18nFactory.getMessage(e.getMessage()));
    }

    @ExceptionHandler(NotLoginException.class)
    public Response notLoginExceptionHandler(NotLoginException e) {
        log.error("NotLoginException", e);
        return getFailureResponse(ErrorEnum.E_NOT_LOGIN, null);
    }

    @ExceptionHandler(RuntimeException.class)
    public Response runtimeExceptionHandler(RuntimeException e) {
        log.error("RuntimeException", e);
        return getFailureResponse(ErrorEnum.E_SYS_RUNTIME_EXCEPTION, e.getMessage());
    }

    private Response getFailureResponse(ErrorEnum errorEnum, String message) {
        if (StringUtils.isBlank(message)) {
            message = errorEnum.getMessage();
        }
        return Response.buildFailure(errorEnum.getCode(), I18nFactory.getMessage(message));
    }

}



